﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Collections.Specialized;
using Easydp.Models.Entities;
using Easydp.Controllers;
namespace Web.Views.AilPay
{
    public partial class AliPayNotify : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            AliPayCode.WriteLog("收到支付宝通知[Database]消息." + DateTime.Now.ToString(), LogType.AliPayNotify);
            #region 获得支付宝的回传通知
            //获得相关支付宝回传的通知
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.Form;

            // Get names of all forms into a string array.
            String[] requestarr = coll.AllKeys;

            //进行排序；
            string[] Sortedstr =AliPayCode.BubbleSort(requestarr);

            //构造待md5摘要字符串；
            string prestr = "";
            for (int i = 0; i < Sortedstr.Length; i++)
            {
                if (Request.Form[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
                {
                    if (i == Sortedstr.Length - 1)
                    {
                        prestr = prestr + Sortedstr[i] + "=" + Request.Form[Sortedstr[i]];
                    }
                    else
                    {
                        prestr = prestr + Sortedstr[i] + "=" + Request.Form[Sortedstr[i]] + "&";
                    }
                }
            }

            //写入日志 
            StringBuilder strMeg = new StringBuilder();
            //Write a line of text
            //sw.WriteLine("通知消息" + prestr);
            strMeg.AppendLine("\r\n通知消息:" + prestr + "&sign=" + Request.Form["sign"] + "&sign_type=" + Request.Form["sign_type"]);

            #endregion

            #region 获取支付宝ATN 结果
            /// <summary>
            /// created by sunzhizhi 2006.5.21,sunzhizhi@msn.com。
            /// </summary>
            string alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?";
            //string partner = "2088002061866935";                        //partner		合作伙伴ID			保留字段
            //string key = "btfhyepobkdkemcxtk2m74tmt85vjnzh";              //partner账户的支付宝安全校验码
            string partner = "2088002166377983";                        //partner		合作伙伴ID			保留字段
            string key = "zhiasv6quoplnykcii4vo3iv3afvh6si";              //partner账户的支付宝安全校验码


            alipayNotifyURL = alipayNotifyURL + "service=notify_verify" + "&partner=" + partner + "&notify_id=" + Request.Form["notify_id"];

            //获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的

            string responseTxt = "";
            try
            {
                responseTxt = AliPayCode.NotifyURL(alipayNotifyURL);
            }
            catch (Exception ex)
            {
                strMeg.AppendLine(string.Format("获取支付宝ATN 结果 出错.验资URL:{0};错误信息:{1}",alipayNotifyURL,ex.Message));
            }

            // 返回实际支付金额       
          

            strMeg.AppendLine("验证消息url:" + alipayNotifyURL + "支付宝验证消息:" + responseTxt);


            
            #endregion

            AliPayCode.WriteLog(strMeg.ToString(), LogType.AliPayNotify);//写入日志

            prestr = prestr + key;

            string mysign = AliPayCode.GetMD5(prestr);

            string sign = Request.Form["sign"];

            string PayMoney =Request.Form["total_fee"].ToString();
            string orderNum =Request.Form["out_trade_no"];
             

            //写入数据库
          //  if (true)　//测试
          if (mysign == sign && responseTxt == "true")   //验证支付发过来的消息，签名是否正确
            {
                //if (true)　//测试
                if (Request.Form["trade_status"] == "TRADE_FINISHED")// WAIT_SELLER_SEND_GOODS  判断支付状态（文档中有枚举表可以参考）            
                {
                    //更新自己数据库的订单语句，请自己填写一下
                    try
                    {
                        TT_Trade trade = new TT_Trade();
                        trade.OrderNumber = orderNum;
                        trade.IsPaid = true;
                        trade.PayAmount = Convert.ToDecimal(PayMoney);
                        trade.BuyerEmail = Request.Form["buyer_email"];
                        trade.NotifyID =  Request.Form["notify_id"];
                        trade.TradeNo = Request.Form["trade_no"];
                        trade.NotifyTime = DateTime.Parse(Request.Form["notify_time"]);
                        trade.SellerEmail = Request.Form["seller_email"];
                        trade.PayType = "收款";

                        bool flag = (new TradeController()).Insert(trade);
                        if (flag)
                            AliPayCode.WriteLog(string.Format("数据库操作;订单号:{0},时间:{1} 数据库写入成功", Request.Form["out_trade_no"], DateTime.Now.ToString()), LogType.AliPayNotify);
                        else
                            AliPayCode.WriteLog(string.Format("数据库操作;订单号:{0},失败时间:{1},通知重发，已作数据库处理", Request.Form["out_trade_no"], DateTime.Now.ToString()), LogType.AliPayNotify);
                    }
                    catch (Exception dataEx)
                    {
                        StringBuilder sbMeg = new StringBuilder("数据库操作：" + DateTime.Now.ToString());
                        sbMeg.Append("; 订单号：");
                        sbMeg.Append(orderNum);
                        sbMeg.AppendLine(";数据库写入失败。");
                        sbMeg.AppendLine("错误消息：" + dataEx.Message);
                        sbMeg.AppendLine("错误方法：" + dataEx.TargetSite.ToString());
                        sbMeg.AppendLine("错误跟踪：" + dataEx.StackTrace);
                        AliPayCode.WriteLog(sbMeg.ToString(), LogType.AliPayNotify);
                        Response.Write("fail");
                        return;
                    }
                    Response.Write("success"); //返回给支付宝消息，成功
                    Response.Flush();
                    Response.End();
                }
                else
                {
                    AliPayCode.WriteLog("数据库操作：" + DateTime.Now.ToString() + "; 订单号：" + orderNum + ";签名错误。", LogType.AliPayNotify);
                    Response.Write("fail");
                    Response.Flush();
                    Response.End();
                }

            }

        }
    }
}
